package csce315.group10.androidapp;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.http.util.ByteArrayBuffer;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

import com.dropbox.client2.DropboxAPI.Entry;
import com.dropbox.client2.exception.DropboxException;
import com.dropbox.client2.exception.DropboxUnlinkedException;

import csce315.group10.R;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class EventList extends ListActivity{
	
	/* private instance variables */
		CustomApp appState;
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	appState = ((CustomApp)getApplicationContext());
	/* get the names of all the events */
	String event_names[] = new String[appState.GetEvents().size()];
	for(int i = 0; i < appState.GetEvents().size(); i++)
	{
		event_names[i] = appState.GetEvents().get(i).get_event_name();
	}
	/* make list fill the whole screen */
	setListAdapter(new ArrayAdapter<String>(this, R.layout.event_list_item, event_names));
	
	ListView lv = getListView();
	/* turn on text filtering,so when the user begins typing, the list will be filtered */
	lv.setTextFilterEnabled(true);
	
	/* set action for when an Event is clicked */
	lv.setOnItemClickListener(new OnItemClickListener() {
	    public void onItemClick(AdapterView<?> parent, View view,
	        int position, long id) {
	    	/* When clicked show the contact info */
	    	openEvent((String) ((TextView) view).getText());
	    	}
		});  
    }
    
    /* open screen with the event info */
    private void openEvent(String name){  
    	Intent intent = new Intent();
    	intent.setClass(this,EventEntry.class);
    	/* set the chosen Event based on name */
    	for(int i = 0; i < appState.GetEvents().size(); i++)
    	{
    		if(appState.GetEvents().get(i).get_event_name() == name){
    			intent.putExtra("event",appState.GetEvents().get(i));
    			break;
    		}
    	}
    	startActivity(intent);
    }
    
    /* create menu */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	/* only create menu with create and delete options if the user is Editor and Chief */
    	if(appState.get_current_user().get_position().equals("Editor And Chief")){
	        MenuInflater inflater = getMenuInflater();
	        inflater.inflate(R.menu.event_list_menu, menu);
	        return true;
    	}
    	return false;
    }
    
    /* set actions for when menu items are selected */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.add_event:     	addEvent();
            							break;
            case R.id.delete_event:		deleteEvent();
            							break;
        }
        return true;
    }
    
    /* start the dialog to get new Event info */
    private void addEvent(){
    	Intent intent = new Intent();
    	intent.setClass(this,AddEventDialog.class);
    	startActivityForResult(intent, 0);
    	
    }
    /* confirm that event should be deleted */
    private void deleteEvent(){
    	Intent intent = new Intent();
    	intent.setClass(this,DeleteEventDialog.class);
    	startActivityForResult(intent, 1);
    }
    
    @Override
	public void onActivityResult(int requestCode,int resultCode, Intent data){
    	/* when prompt for new event returns */
    	/* if back button was pressed then return */
    	if(resultCode != Activity.RESULT_OK){
    		return;
    	}
      if(requestCode == 0){
    	 /* create new event, but first check to see if already exists */
    	  if(data.getBooleanExtra("exists", true)){
    		  Toast.makeText(this, "Event With That Name Already Exists" , Toast.LENGTH_LONG).show();
    	  }else{
    		  appState.GetEvents().add(new Event(data.getStringExtra("event_name"),data.getStringExtra("event_date"),data.getStringExtra("event_time"),
    				  data.getStringExtra("contact_name"),data.getStringExtra("contact_phone"),data.getStringExtra("staffer"),data.getStringExtra("location"),
    				  data.getStringExtra("notes")));
    	  }
      }else if(requestCode == 1){
    	  /* delete event */
    	  for(int i = 0; i < appState.GetEvents().size(); i++){
    		  if(appState.GetEvents().get(i).get_event_name().equals(data.getStringExtra("event_name")) ){
    			  appState.GetEvents().remove(i);
    			  break;
    		  }
    	  }  
      }
      /* refresh display updated events */
      startActivity(getIntent()); 
      finish();
    }
    
    public void onDestroy(){
    	super.onDestroy();
    	final String TAG = YearBookAppActivity.class.getCanonicalName();
		Log.i(TAG, "Write AppState to file.");
        Serializer serial = new Persister();
    	File sdcardFile = new File("/sdcard/customappData.xml");

    	try {
			serial.write(appState, sdcardFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
		// Uploading content.
		File file = new File("/sdcard/customappData.xml");
		FileInputStream fis;
    	BufferedInputStream bis;
		try {
			fis = new FileInputStream(file);
			bis = new BufferedInputStream(fis);
			ByteArrayBuffer baf = new ByteArrayBuffer(50);
	        int current = 0;
	        while ((current = bis.read()) != -1) {
	        	baf.append((byte) current);
	        }
	        ByteArrayInputStream inputStream = new ByteArrayInputStream(baf.toByteArray());
	        Entry newEntry = appState.get_dropbox().putFileOverwrite("/customappData.xml",inputStream,
			           baf.toByteArray().length, null);
	        Log.i("DbLog", "The uploaded file's rev is: " + newEntry.rev);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			 Log.d("Client", "Error: " + e);
		}catch (DropboxUnlinkedException e) {
		   // User has unlinked, ask them to link again here.
		   Log.e("DbLog", "User has unlinked.");
		} catch (DropboxException e) {
		   Log.e("DbLog", "Something went wrong while uploading.");
		}
    }

}